#import "HHHttpEnv.h"

@interface HHHttpEnv ()

/// 环境变量，key-value，根据环境从主工程BCHttpCom_Env.json读取。0:线上,1:测试, 2:预发
@property (nonatomic, strong, readwrite) NSDictionary *envMap;
/// api 接口
@property (nonatomic, strong, readwrite) NSDictionary *apiMap;
///当前环境，默认0:线上,1:测试, 2:预发
@property (nonatomic, assign, readwrite) NSInteger currentEnv;
/// 接口host
@property (nonatomic, copy, readwrite) NSString *httpApi_host;
/// 文件上传URL，一般是七牛地址
@property (nonatomic, copy, readwrite) NSString *httpApi_fileHost;

@end

@implementation HHHttpEnv

static HHHttpEnv *kEnvInstance;
+ (instancetype)shared {
    static dispatch_once_t kOnceToken;
    dispatch_once(&kOnceToken, ^{
        kEnvInstance = [[[self class] alloc] init];
    });
    return kEnvInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.currentEnv = -1;
        [self changeAppCurrentENV:[self currentUserENV]];
    }
    return self;
}
- (NSInteger)currentUserENV {
    NSInteger currentENV = kBCHttp_ENV_OnLine; //默认线上
    NSNumber *envNumber = [[NSUserDefaults standardUserDefaults] valueForKey:@"kHHHttp_env"];

    if (envNumber) {
        currentENV = [envNumber integerValue];
    }
    return currentENV;
}

///MARK: - 环境配置
- (void)changeAppCurrentENV:(NSInteger)env {
    self.currentEnv = env;
    NSString *envFile = @"BCHttpCom_Env";
    if (env > 0) {
        envFile = [NSString stringWithFormat:@"BCHttpCom_Env%@", @(env)];
    }
    NSString *filePath = [[NSBundle mainBundle] pathForResource:envFile ofType:@"json"];
    NSData *jsonData = [[NSData alloc] initWithContentsOfFile:filePath];
    if (jsonData) {
        _envMap = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
    } else {
#ifdef DEBUG
        NSLog(@"[BCComConfig] BCComConfig_Env%@.json is empty", @(env));
#endif
    }
    self.httpApi_fileHost = _envMap[@"api_fileHost"];

    // 存储
    [[NSUserDefaults standardUserDefaults] setValue:@(env) forKey:@"kHHHttp_env"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

///MARK: - API
-(NSDictionary *)apiMap {
    if (!_apiMap) {
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"BCHttpCom_Api" ofType:@"json"];
        NSData *jsonData = [[NSData alloc] initWithContentsOfFile:filePath];
        if (jsonData) {
            _apiMap = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
        } else {
#ifdef DEBUG
            NSLog(@"[BCComConfig] BCComConfig.json is empty");
#endif
        }
    }
    return _apiMap;
}
- (NSString *)mappingPath:(NSString *)key {
    if (self.apiMap && self.apiMap[key]) {
        return self.apiMap[key];
    }
    return key;
}

- (NSInteger)envRole {
    return [_envMap[@"role"] integerValue];
}
///MARK: -分类服务器地址
/// 默认群组接口
- (NSString *)apiHost {
    return [self valueForEnv:@"api_host"];
}
/// 医生服务地址
- (NSString *)webHost {
    return [self valueForEnv:@"web_host"];
}
/// api 签名
- (NSString *)apiSignKey {
    return [self valueForEnv:@"api_signKey"];
}
/// 参数签名
- (NSString *)paramsSignKey {
    return [self valueForEnv:@"params_signKey"];
}

/// 环境app key
- (NSString *)emAppkey{
    return [self valueForEnv:@"em_appkey"];
}

- (NSString *)valueForEnv:(NSString *)key {
    if (_envMap[key]) {
        return _envMap[key];
    }
    NSLog(@"网络配置文件中未查找到【 %@】",key);
    return @"";
}

///MARK: - help
+ (NSString *)urlComposePath:(NSString * _Nullable)paths, ... {
    NSMutableString *mString = [[NSMutableString alloc] initWithString:paths];
    va_list args;
    va_start(args, paths);
    if (paths.length) {
        NSString *addstring = nil;
        while ((addstring = va_arg(args, NSString *))) {
            [mString appendFormat:@"/%@",addstring];
        }
    }
    va_end(args);
    
    return mString;
}
+ (NSString *)url:(NSString *)url compnentParams:(NSDictionary *)params {
    
    NSMutableString *mString = [[NSMutableString alloc] initWithString:url];
    NSArray *keyArr = params.allKeys;
    for (NSInteger i = 0; i < keyArr.count; i++) {
        NSString *key = keyArr[i];
        // Encoding
        NSString *valueStr = [NSString stringWithFormat:@"%@", params[key]];
        NSString *encodValue = [valueStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        if (i > 0) {
            [mString appendFormat:@"&%@=%@", key, encodValue];
        } else {
            [mString appendFormat:@"?%@=%@", key, encodValue];
        }
    }
    return mString;
}
@end
